package coder.apps;

import java.io.File;

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFileFormat.Type;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.TargetDataLine;

public class JWavRecorder extends Thread {

    private TargetDataLine		 	m_line;
    private AudioFileFormat.Type 	m_targetType;
    private AudioInputStream	 	m_audioInputStream;
    private File 					m_outputFile;
    private AudioFormat 			m_targetAudioFormat;
    
    public JWavRecorder(TargetDataLine m_line, Type m_tType,File m_outFile,AudioFormat m_aFormat) {
        this.m_line = m_line;
        this.m_targetType = m_tType;
        this.m_audioInputStream = new AudioInputStream(m_line);
        this.m_outputFile = m_outFile;
        this.m_targetAudioFormat = m_aFormat;
    }

    public void run()
    {
    	startLine();
        try {
            AudioSystem.write(m_audioInputStream,m_targetType,m_outputFile);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private void startLine() {
    	
    	try {
			m_line.open(m_targetAudioFormat);
		} catch (LineUnavailableException e) {
			e.printStackTrace();
			System.exit(1);
		}
    	m_line.start();
    }
    
    public void stopLine(){
    	m_line.stop();
    	m_line.close();
    }
    
    public static void main(String args[]) {
        File outputFile = new File(System.getenv("USERPROFILE")+"/Desktop/audiorec.wav");
        AudioFormat audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 44100.0F, 16, 2, 4, 44100.0F, false);
        TargetDataLine targetDataLine = null;
        AudioFileFormat.Type targetType = AudioFileFormat.Type.WAVE;
        
        try {
            targetDataLine = AudioSystem.getTargetDataLine(null);
        }
        catch (LineUnavailableException e) {
            System.out.println("unable to get a recording line");
            e.printStackTrace();
            System.exit(1);
        }
        JWavRecorder j = new JWavRecorder(targetDataLine, targetType, outputFile, audioFormat);
        System.out.println("Press ENTER to start the recording.");
        try {
            System.in.read();            
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        j.start();
        System.out.println("Recording...");
        System.out.println("Press ENTER to stop the recording.");
        try {
            System.in.read();
            System.in.read();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        j.stopLine();
        System.out.println("Recording stopped.");
    }
}